package com.example.sbeducation.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.sbeducation.common.Result;
import com.example.sbeducation.dto.ChatMessageDTO;
import com.example.sbeducation.entity.ChatMessage;
import com.example.sbeducation.service.ChatMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 聊天消息控制器
 */
@RestController
@RequestMapping("/api/chat")
public class ChatMessageController {

  @Autowired
  private ChatMessageService chatMessageService;

  /**
   * 发送消息
   */
  @PostMapping("/message")
  public Result<Long> sendMessage(@Valid @RequestBody ChatMessageDTO chatMessageDTO) {
    Long messageId = chatMessageService.sendMessage(chatMessageDTO);
    return Result.success(messageId);
  }

  /**
   * 获取聊天历史记录
   */
  @GetMapping("/history")
  public Result<Page<ChatMessage>> getChatHistory(
      @RequestParam Long senderId,
      @RequestParam Long receiverId,
      @RequestParam(defaultValue = "1") Integer page,
      @RequestParam(defaultValue = "20") Integer size) {
    Page<ChatMessage> chatHistory = chatMessageService.getChatHistory(senderId, receiverId, page, size);
    return Result.success(chatHistory);
  }

  /**
   * 标记消息为已读
   */
  @PutMapping("/read/{messageId}")
  public Result<Void> markAsRead(@PathVariable Long messageId) {
    chatMessageService.markAsRead(messageId);
    return Result.success("标记成功");
  }

  /**
   * 标记用户所有消息为已读
   */
  @PutMapping("/read/all/{receiverId}")
  public Result<Void> markAllAsRead(@PathVariable Long receiverId) {
    chatMessageService.markAllAsRead(receiverId);
    return Result.success("标记成功");
  }

  /**
   * 获取用户未读消息数量
   */
  @GetMapping("/unread/count/{receiverId}")
  public Result<Integer> getUnreadCount(@PathVariable Long receiverId) {
    Integer count = chatMessageService.getUnreadCount(receiverId);
    return Result.success(count);
  }

  /**
   * 获取用户未读消息
   */
  @GetMapping("/unread/{receiverId}")
  public Result<List<ChatMessage>> getUnreadMessages(@PathVariable Long receiverId) {
    List<ChatMessage> unreadMessages = chatMessageService.getUnreadMessages(receiverId);
    return Result.success(unreadMessages);
  }
}